from appium import webdriver
import os

from framework.basetest import BaseTest


class AppiumBaseTest(BaseTest):

    def setUp(self, config, **kwargs):
        super().setUp(config)

    def tearDown(self):
        self.logger.info('自动化测试程序结束')
        for method, error in self._outcome.errors:
            if error:
                self.logger.error(error[1])
                filename = os.path.join(os.path.sep, self.test_data_path, f'{self.test_method_name}.png')
                if not os.path.exists(self.test_data_path):
                    os.makedirs(self.test_data_path)
                if self.driver is not None and hasattr(self.driver, 'save_screenshot'):
                    self.logger.info(f'Create screenshot: {filename}')
                    self.driver.save_screenshot(filename)
        if self.driver:
            self.driver.quit()

    def init_driver_by_device_name(self, config, **kwargs):
        if config['mobileapp']['appiumServer'].lower() == 'headspin':
            self.logger.info('在HeadSpin上运行移动端自动化测试')
            device_name = None
            for k, v in kwargs.items():
                self.logger.debug(f'Optional arguments {k} = {v}')
                if k == 'deviceName':
                    device_name = v

            if device_name is None:
                raise ValueError('自动化测试将在HeadSpin上运行，请提供设备名称 deviceName?')

            # 从HeadSpin API 获取基础 Desire Capabilities
            udid = self.hs_api.get_device_udid_by_name(device_name)
            desire_cap = self.hs_api.get_device_capabilities(udid)
            appium_url = self.hs_api.get_driver_url_for_device(udid)

            # 添加本地 Desire Capabilities 参数
            desire_cap_local = self.hs_api.get_device_local_config_by_udid(udid)

            # 整合本地与hs desire capability
            desire_cap.update(desire_cap_local)
        else:
            self.logger.info('在本地运行移动端自动化测试')
            desire_cap = config['mobileapp']['local']['desired_caps']
            appium_url = config['mobileapp']['appiumServer']

        self.logger.info(f'The appium driver url: {appium_url}')
        self.logger.info(f'The desire cap: {desire_cap}')
        self.driver = webdriver.Remote(appium_url, desire_cap)
